package cn.school.web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.school.mybatis.pojo.Admin;
import cn.school.mybatis.service.AdminService;

/**
 * Servlet implementation class AdminLoginServlet
 */
@WebServlet("/adminlogin")
public class AdminLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdminLoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	private AdminService adminService = new AdminService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// application
		ServletContext sc = super.getServletContext();
		// >>>sc.getRealPath(arg0)
		request.setCharacterEncoding("utf-8");
		String u = request.getParameter("userName");
		String p = request.getParameter("userPass");
		Admin admin = adminService.login(u, p);
		if (admin != null) {
			HttpSession s = request.getSession();
			s.setAttribute("USER_LOGIN", admin);

			// 转发
			request.getRequestDispatcher("/pages/welcome.jsp").forward(request, response);
			return;
		}

		response.sendRedirect("pages/fail.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
